//
//  MineRegistController.swift
//  HappyEat
//
//  Created by ctx2016 on 17/1/20.
//  Copyright © 2017年 陌路是我. All rights reserved.
//

import UIKit
import SwiftyJSON

class MineRegistController: UIViewController ,UITextFieldDelegate{
    
    var userDefault:UserDefaults = UserDefaults.standard
    
    var codingStr:String = ""
    
    var viewFrame:CGRect = .zero
    
    var counDown:CountDown = CountDown.init()
    
    let titleNames:[String] = ["请输入手机号码","请输入您的验证码","请设置密码(由6-14位数字字母组成)","请确认密码(由6-14位数字字母组成)","请填入您收到的邀请码(选填)"]
    
    let imageNames:[String] = ["Mine-zhanghu","yanzhengma","mima","mima","mima"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setNavi()
    }
}
extension MineRegistController{
    //MARK:设置导航栏选项
    func setNavi(){
        self.navigationItem.title = "注册账号"
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black]
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "", imagStr: "ic_back", fontSize: 14, target: self, action: #selector(leftBarButtonAction))
    }
    //MARK:LeftBarButtonAction
    func leftBarButtonAction(){
        self.navigationController!.popViewController(animated: false)
    }
    func setUI(){
        let tapHideKeyBoard:UITapGestureRecognizer = UITapGestureRecognizer.init()
        self.view.addGestureRecognizer(tapHideKeyBoard)
        tapHideKeyBoard.addTarget(self, action: #selector(hideKeyBoard))
        self.viewFrame = self.view.frame
        for i in 0 ..< titleNames.count {
            let iconImage:UIImageView = UIImageView.init(image: UIImage.init(named: imageNames[i]))
            let textFielld:UITextField = UITextField.init()
            
            let downView:UIView = UIView.init()
            self.view.addSubview(iconImage)
            self.view.addSubview(textFielld)
            self.view.addSubview(downView)
            downView.backgroundColor = .gray
            iconImage.snp.makeConstraints({ (make) in
                make.left.equalTo(16)
                make.size.equalTo(CGSize.init(width: 15, height: 20))
                make.top.equalTo(64+15 + 50*i)
            })
            textFielld.snp.makeConstraints({ (make) in
                make.left.equalTo(iconImage.snp.right).offset(12)
                make.top.equalTo(17 + 64 + 50*i)
                make.height.equalTo(16)
                make.right.equalTo(-16)
            })
            textFielld.font = UIFont.systemFont(ofSize: 12)
            textFielld.placeholder = titleNames[i]
            textFielld.tag = 100+i
            downView.tag = 10+i
            textFielld.delegate = self
            downView.snp.makeConstraints({ (make) in
                make.left.equalTo(48)
                make.right.equalTo(-16)
                make.height.equalTo(0.5)
                make.top.equalTo(textFielld.snp.bottom).offset(16)
            })
            if i == 1{
                let getYzmButton:UIButton = UIButton.init()
                self.view.addSubview(getYzmButton)
                let label:UILabel = UILabel.init()
                getYzmButton.snp.makeConstraints({ (make) in
                    make.right.equalTo(-16)
                    make.bottom.equalTo(downView.snp.top).offset(-9)
                    make.height.equalTo(32)
                    make.width.equalTo(label.width(forText: "获取验证码", withFontSize: 14, withTextHeight: 32)+20)
                })
                getYzmButton.addTarget(self, action: #selector(getYzmAction(_:)), for: .touchUpInside)
                getYzmButton.setTitle("获取验证码", for: .normal)
                getYzmButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                getYzmButton.backgroundColor = .red
                getYzmButton.setTitleColor(.white, for: .normal)
                getYzmButton.layer.cornerRadius = 5
            }
        }
        let lastView:UIView  = self.view.viewWithTag(14)!
        let iconButton:UIButton = UIButton.init()
        iconButton.setImage(UIImage.init(named: "tongyi"), for: .normal)
        iconButton.setImage(UIImage.init(named: "tongyi_c"), for: .selected)
        iconButton.addTarget(self, action: #selector(allowProtocalAction(_:)), for: .touchUpInside)
        self.view.addSubview(iconButton)
        iconButton.snp.makeConstraints { (make) in
            make.left.equalTo(16)
            make.size.equalTo(CGSize.init(width: 8, height: 8))
            make.top.equalTo(lastView.snp.bottom).offset(16)
        }
        
        let allowLabel:UILabel = UILabel.init()
        self.view.addSubview(allowLabel)
        allowLabel.snp.makeConstraints { (make) in
            make.left.equalTo(iconButton.snp.right).offset(5)
            make.top.equalTo(lastView.snp.bottom).offset(12)
            make.height.equalTo(16)
            make.right.equalTo(-16)
        }
        allowLabel.text = "已同意协议"
        allowLabel.font = UIFont.systemFont(ofSize: 16)
        let registButton:UIButton = UIButton.init()
        self.view.addSubview(registButton)
        registButton.snp.makeConstraints { (make) in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(40)
            make.top.equalTo(allowLabel.snp.bottom).offset(12)
        }
        registButton.setTitle("立即注册", for: .normal)
        registButton.setTitleColor(.white, for: .normal)
        registButton.backgroundColor = .red
        registButton.addTarget(self, action: #selector(registButtonAction), for: .touchUpInside)
    }

    //MARK:注册按钮事件
    func registButtonAction(){
        let phoneTextField:UITextField = self.view.viewWithTag(100) as!UITextField
        let yzmTextField:UITextField = self.view.viewWithTag(101) as!UITextField
        let passWordField:UITextField = self.view.viewWithTag(102) as!UITextField
        let rePasswordTextFild:UITextField = self.view.viewWithTag(103) as!UITextField
        let yqmTextField:UITextField = self.view.viewWithTag(104) as!UITextField
        //判断手机是否合法
        var phoeNum:NSString = phoneTextField.text as NSString? ?? ""
        let whiteSet = NSCharacterSet.whitespacesAndNewlines
        phoeNum = phoeNum.trimmingCharacters(in: whiteSet) as NSString
        var yzmStr:NSString = yzmTextField.text as NSString? ?? ""
        yzmStr = yzmStr.trimmingCharacters(in: whiteSet) as NSString
        var passWordStr:NSString = passWordField.text as NSString? ?? ""
        passWordStr = passWordStr.trimmingCharacters(in: whiteSet) as NSString
        var rePassWordStr:NSString = rePasswordTextFild.text as NSString? ?? ""
        rePassWordStr = rePassWordStr.trimmingCharacters(in: whiteSet) as NSString
        var yqmStr:NSString = yqmTextField.text as NSString? ?? ""
        yqmStr = yqmStr.trimmingCharacters(in: whiteSet) as NSString
        
        //验证码事件
        if !(phoeNum != "")&&(yzmStr != "")&&(passWordStr != "")&&(rePassWordStr != ""){
            //信息录入不全
            return
        }
        var codinTools = CodingStrinTool.shareInstance
        if !codinTools.isRegexPhoneNum(phoeNum as String) {
            //手机号码格式错误
            return
        }
        if  !codinTools.stringEquto(passWordStr as String, rePassWordStr as String){
            //密码不相同
            return
        }
        
        
        
        let netRequst:NetworkRequest = NetworkRequest.shareInstance
        let dic:[String:String] = ["phone":phoeNum as String,
                                   "password":passWordStr as String,
                                   "verifyCode":codingStr,
                                   "inviteCode":yqmStr as String]
        netRequst.postRequest(urlString: Regist_URL, params: dic, success: { (success) in
            let returnDic = JSON(success)
            print(returnDic["status"].stringValue)
            if returnDic["status"].stringValue == "SUCCESS" {
                let dataDic = returnDic["data"]
//                let idStr:String = dataDic["id"].stringValue
//                print(idStr)
//                print(dataDic["id"].stringValue)
//                print(dataDic["phone"].stringValue)
//                print(dataDic["nickname"].stringValue)
//                print(dataDic["headImg"].stringValue)
//                print(dataDic["registerTime"].stringValue)
//                print(dataDic["lastLoginTime"].stringValue)
//                print(dataDic["status"].stringValue)
//                print(dataDic["balance"].stringValue)
//                print(dataDic["points"].stringValue)
//                print(dataDic["inviteCode"].stringValue)
//                print(dataDic["verifyCode"].stringValue)
                self.userDefault.set(dataDic["id"].stringValue, forKey: ID)
                self.userDefault.set(dataDic["phone"].stringValue , forKey: PHONE)
                self.userDefault.set(passWordStr, forKey: PASSWWORD)
                self.userDefault.set(dataDic["nickname"].stringValue, forKey: NICKNAME)
                self.userDefault.set(dataDic["headImg"].stringValue, forKey: HEADIMGE)
                self.userDefault.set(dataDic["registerTime"].stringValue, forKey: REGISTTIME)
                self.userDefault.set(dataDic["lastLoginTime"].stringValue, forKey: LASTLOGINTIME)
                self.userDefault.set(dataDic["status"].stringValue, forKey: STATUS)
                self.userDefault.set(dataDic["balance"].stringValue, forKey: BALANCE)
                self.userDefault.set(dataDic["points"].stringValue, forKey: POINTS)
                self.userDefault.set(dataDic["inviteCode"].stringValue, forKey: INVITECODE)
                self.userDefault.set(dataDic["verifyCode"].stringValue, forKey: VERIFYCODE)
                self.userDefault.synchronize()
                
                self.navigationController!.popToRootViewController(animated: true)
            }
            else if returnDic["status"].stringValue == "ERROR"{
                print("-------------")
               print(returnDic["error"].stringValue)
            }
            }) { (error) in
                print(error)
                //请求返回错误
        }
//        self.navigationController?.popToRootViewController(animated: true)
    }
    func allowProtocalAction(_ button:UIButton){
        button.isSelected = !button.isSelected
        if button.isSelected{
            //执行事件
        }
    }
    //MARK:getYzmAction
    func getYzmAction(_ button:UIButton){
        let timeOut:Double = 60.0
        self.startTimeAndEndTime(startDate: Date.init(), endDate: Date.init(timeIntervalSinceNow: timeOut), button: button)
    }
    //MARK:倒计时验证码
    func startTimeAndEndTime(startDate:Date,endDate:Date,button:UIButton){
        //获取验证码接口调用
        let phoneTextField:UITextField = self.view.viewWithTag(100) as!UITextField
        //判断手机是否合法
        var phoeNum:NSString = phoneTextField.text as NSString? ?? ""
        let whiteSet = NSCharacterSet.whitespacesAndNewlines
        phoeNum = phoeNum.trimmingCharacters(in: whiteSet) as NSString
        let strTool:CodingStrinTool = CodingStrinTool.shareInstance
        if !strTool.isRegexPhoneNum(phoeNum as String) {
            //请输入正确的手机号码
            return
        }
      weak var WeakSelf = self
        WeakSelf?.counDown.countDown(withStratDate: startDate, finish: endDate, complete: { (day:Int,hour:Int,minus:Int, second:Int) in
            let toastInterge:Int = day*24*3600 + hour*3600 + minus*60 + second
            if toastInterge == 0{
                button.isEnabled = true
               button.setTitle("获取验证码", for: .normal)
            }else{
                button.isEnabled = false
                button.setTitle(String(toastInterge)+"秒后获取", for: .normal)
            }
        })

        let netrequst:NetworkRequest = NetworkRequest.shareInstance
        let dic:[String:String] = ["phone":phoeNum as String]
        netrequst.postRequest(urlString: GetCoding_URl, params: dic, success: { (success) in
            print("first--\(success)")
            print("second\(JSON(success))")
            let dic = JSON(success)
            if dic["status"] == "SUCCESS" {
                self.codingStr = "\(dic["data"])"
                print(self.codingStr)
            }
            }){ (error) in
                print(error)
        }
    }
    //MARK:textfieldDelegate
    
    
    
    
    
    

    func textFieldDidBeginEditing(_ textField: UITextField) {
        let teptextFiled:UITextField = self.view.viewWithTag(104) as! UITextField
        if teptextFiled == textField {
            //视图上移动
            var orignFrame:CGRect = self.viewFrame
            orignFrame.origin.y = self.viewFrame.origin.y - 80
            UIView.animate(withDuration: 0.3, animations: { 
                self.view.frame = orignFrame
            })
        }else{
            UIView.animate(withDuration: 0.3, animations: { 
                self.view.frame = self.viewFrame
            })
        }
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        UIView.animate(withDuration: 0.3) {
            self.view.frame = self.viewFrame
        }
        return true
    }
    func hideKeyBoard(){
//        self.phoneTextField.resignFirstResponder()
//        self.mimaTextField.resignFirstResponder()
        for i in 100 ... 104 {
            let textField:UITextField = self.view.viewWithTag(i) as!UITextField
            textField.resignFirstResponder()
        }
        UIView.animate(withDuration: 0.3) {
            self.view.frame = self.viewFrame
        }
    }
}

